<template>
  <view class="product-detail">
    <!-- 商品图片 -->
    <image :src="product.image" mode="aspectFill" class="product-image"></image>
    
    <!-- 商品信息 -->
    <view class="product-info">
      <view class="product-name">{{product.name}}</view>
      <view class="product-desc">{{product.description}}</view>
      <view class="product-score">{{product.score}}积分</view>
      <view class="product-stock">库存：{{product.stock}}件</view>
      <view class="product-sales">已兑换：{{product.sales}}件</view>
    </view>
    
    <!-- 兑换按钮 -->
    <view class="exchange-btn" @click="handleExchange">
      <text>立即兑换</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { scoreMallData } from '@/data/score_mall.js'

const product = ref({})
const userScore = ref(scoreMallData.userScore)

onMounted(() => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const id = currentPage.$page?.options?.id
  
  if (id) {
    const foundProduct = scoreMallData.products.find(item => item.id === Number(id))
    if (foundProduct) {
      product.value = foundProduct
    }
  }
})

const handleExchange = () => {
  if (userScore.value.availableScore < product.value.score) {
    uni.showToast({
      title: '积分不足',
      icon: 'none'
    })
    return
  }
  
  if (product.value.stock <= 0) {
    uni.showToast({
      title: '库存不足',
      icon: 'none'
    })
    return
  }
  
  uni.showModal({
    title: '确认兑换',
    content: `确定要使用${product.value.score}积分兑换${product.value.name}吗？`,
    success: (res) => {
      if (res.confirm) {
        // 模拟兑换成功
        userScore.value.availableScore -= product.value.score
        product.value.stock -= 1
        product.value.sales += 1
        
        uni.showToast({
          title: '兑换成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    }
  })
}
</script>

<style lang="scss">
.product-detail {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .product-image {
    width: 100%;
    height: 500rpx;
  }
  
  .product-info {
    background-color: #fff;
    padding: 30rpx;
    margin-top: 20rpx;
    
    .product-name {
      font-size: 36rpx;
      font-weight: bold;
    }
    
    .product-desc {
      font-size: 28rpx;
      color: #666;
      margin: 20rpx 0;
    }
    
    .product-score {
      color: #ff6b6b;
      font-size: 40rpx;
      font-weight: bold;
      margin: 20rpx 0;
    }
    
    .product-stock,
    .product-sales {
      font-size: 24rpx;
      color: #999;
      margin-top: 10rpx;
    }
  }
  
  .exchange-btn {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100rpx;
    background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    font-weight: bold;
  }
}
</style> 